package BinaryTree;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

public class PostorderTraversal145 {

    public List<Integer> postorderTraversal1(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<>();
        ArrayDeque<TreeNode> stack1 = new ArrayDeque<>();
        ArrayDeque<TreeNode> stack2 = new ArrayDeque<>();
        if(root == null){
            return list;
        }else if(root.left == null && root.right == null){
            list.add(root.val);
            return list;
        }
        stack1.push(root);
        while(!stack1.isEmpty()){
            TreeNode pop = stack1.pop();
            stack2.push(pop);
            if(pop.left != null){
                stack1.push(pop.left);
            }
            if(pop.right != null){
                stack1.push(pop.right);
            }
        }

        while(!stack2.isEmpty()){
            list.add(stack2.pop().val);
        }
        return list;
    }

    public List<Integer> postorderTraversal(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<>();
        postorder(root,list);
        return list;
    }

    public void postorder(TreeNode root, ArrayList<Integer> list) {
        if(root == null){
            return;
        }
        postorder(root.left,list);
        postorder(root.right,list);
        list.add(root.val);
    }
}
